package monster.com.cvh.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import monster.com.cvh.R;
import monster.com.cvh.activity.base.PermissionActivity;
import monster.com.cvh.adapter.CommentDetailsAdapter;
import monster.com.cvh.bean.CommentDetailsBean;
import monster.com.cvh.bean.GetCommentInfoBean;
import monster.com.cvh.bean.MessageEvent;
import monster.com.cvh.bean.NewsDetailBean;
import monster.com.cvh.bean.PostBean;
import monster.com.cvh.bean.PublishCommentBean;
import monster.com.cvh.util.EditTextDialog;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.SPUtils;
import monster.com.cvh.util.StatusBarUtil;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @author: monster
 * @data: 2018/4/3
 * @function: 评论详情页面
 */
public class CommentDetailsActivity extends PermissionActivity {
    private static final String TAG = "lixiaofei";
    @BindView(R.id.iv_news_details_title_back)
    ImageView mIvNewsDetailsTitleBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.details_title)
    RelativeLayout detailsTitle;
    @BindView(R.id.recyclerview_activity_comment_details)
    RecyclerView mRecyclerviewActivityCommentDetails;
    @BindView(R.id.rf_activity_comment_details)
    SmartRefreshLayout rfActivityCommentDetails;
    @BindView(R.id.tv_comment_details)
    TextView tvCommentDetails;
    private List<CommentDetailsBean.DataBean> mDatas = new ArrayList<>();
    private int pageNum = 0;
    private NewsDetailBean.DataBean item;
    private CommentDetailsAdapter adapter;
    private LayoutInflater inflater;
    private ViewGroup parentView;
    private List<CommentDetailsBean.DataBean> data;
    private int comment_id;
    private BaseBottomDialog mDialog;
    private EditText commentContext;
    private String time;
    private String token;
    private boolean isPraise;
    private int user_id;
    private String user_name;
    private String context;
    private int replyNum;
    private String icon_url;
    private int praiseNum;
    private GetCommentInfoBean.DataBean dataBean;
    private TextView praise;
    private ImageView imgPraise;

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_comment_details;
    }

    /**
     * 注册 EventBus
     */
    @Override
    protected void initEvent() {
        EventBus.getDefault().register(this);

    }

    /**
     * 销毁EventBus
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    /**
     * 接收事件
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        Log.i(TAG, "Event: "+messageEvent.getMessage());
        mDatas.clear();
        OkGo.<String>get(MyConstant.GETCOMMENTS).params("token", SPUtils.getString(CommentDetailsActivity.this, "token", ""))
                .params("page_index", 0).params("comment_id", item.getId()).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Gson gson = new Gson();
                CommentDetailsBean commentDetailsBean = gson.fromJson(s, CommentDetailsBean.class);
                data = commentDetailsBean.getData();
                if (data != null) {
                    mDatas.addAll(data);
                }
                mRecyclerviewActivityCommentDetails.setLayoutManager(new LinearLayoutManager(CommentDetailsActivity.this));
                adapter = new CommentDetailsAdapter(R.layout.item_comment_details, mDatas,getSupportFragmentManager());
                mRecyclerviewActivityCommentDetails.setAdapter(adapter);
                deleteComment();
                initHead();
            }
        });
    }


    @Override
    protected void initData() {
        //修改状态栏颜色
        StatusBarUtil.setStatusBarLightMode(CommentDetailsActivity.this, Color.WHITE);
        token = SPUtils.getString(CommentDetailsActivity.this, "token", "");
        //设置标题
        mTvTitle.setText("评论详情");
        //获取上个页面传过来的数据
        switch (getIntent().getIntExtra("identify",-1)){
            case 1:
                //新闻跳过来
                item = (NewsDetailBean.DataBean) getIntent().getSerializableExtra("item");
                time = getIntent().getStringExtra("time");
                isPraise = item.isIs_praise();
                user_id = item.getUser_id();
                user_name = item.getUser_name();
                context = item.getContent();
                replyNum = item.getReply();
                icon_url = item.getIcon_url();
                praiseNum = item.getPraise();
                //往第一个条目塞数据
                //获取评论
                comment_id = item.getId();
                Log.i(TAG, "initData: " + praiseNum);
                Log.i(TAG, "initData: "+time);
                break;
            case 2:
                //点赞消息跳过来
                comment_id = getIntent().getIntExtra("id",-1);
                isPraise = getIntent().getBooleanExtra("isPraise",false);
                time = getIntent().getStringExtra("time");
                user_id = getIntent().getIntExtra("userId",-1);
                user_name = getIntent().getStringExtra("userName");
                context = getIntent().getStringExtra("content");
                replyNum = getIntent().getIntExtra("reply",-1);
                icon_url = getIntent().getStringExtra("iconUrl");
                praiseNum = getIntent().getIntExtra("praise",-1);
                break;
            case 3:
                //评论跳过来
                dataBean = (GetCommentInfoBean.DataBean) getIntent().getSerializableExtra("item");
                time = getIntent().getStringExtra("time");
                comment_id = dataBean.getId();
                isPraise = dataBean.isIs_praise();
                user_id = dataBean.getUser_id();
                user_name = dataBean.getUser_name();
                context = dataBean.getContent();
                replyNum = dataBean.getReply();
                icon_url = dataBean.getIcon_url();
                praiseNum = dataBean.getPraise_count();
                break;
        }
        getServiceComment();
        rfActivityCommentDetails.setEnableRefresh(false);
        rfActivityCommentDetails.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageNum++;
//                newsDetailAdapter.removeAllHeaderView();
                getMoreCommetn();
                adapter.notifyDataSetChanged();
                refreshlayout.finishLoadmore(500);
                if (data.size() < 20) {
                    showToastLong("没有更多评论");

                }
            }
        });
    }

    /**
     * 删除 评论
     */
    private void deleteComment() {
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(final BaseQuickAdapter adapter, View view, final int position) {
                switch (view.getId()) {
                    case R.id.tv_item_comment_delete:
                        //删除评论
                        new AlertDialog.Builder(CommentDetailsActivity.this).setTitle("删除本条").setMessage("确认要删除本条数据吗？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Log.i(" lixiaofei", "我是当前位置: " + position);
                                OkGo.<String>delete(MyConstant.DELETE_COMMENT).params("comment_id", mDatas.get(position).getId()).params("token", SPUtils.getString(CommentDetailsActivity.this, "token", ""))
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onSuccess(String s, Call call, Response response) {
                                                Gson gson = new Gson();
                                                PostBean deleteBean = gson.fromJson(s, PostBean.class);
                                                switch (deleteBean.getCode()) {
                                                    case 1:
                                                        //删除成功
                                                        showToastLong("删除成功");
                                                        adapter.getData().remove(position);
                                                        adapter.notifyDataSetChanged();
                                                        break;
                                                }
                                            }
                                        });
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).show();

                        break;
                    case R.id.tv_item_comment_detals_reply:
                        //回复
                        comment_id = mDatas.get(position).getId();
                        if (token.equals("") || token == null){
                            startActivity(new Intent(CommentDetailsActivity.this,LoginActivity.class));
                            finish();
                        }else {
                            tipComment();
                        }
                        break;
                }
            }
        });
    }

    /**
     * 获取评论
     */
    private void getServiceComment() {
        switch (getIntent().getIntExtra("identify",-1)){
            case 1:
                //新闻跳过来
                item = (NewsDetailBean.DataBean) getIntent().getSerializableExtra("item");
                comment_id = item.getId();
                break;
            case 2:
                //点赞消息跳过来
                comment_id = getIntent().getIntExtra("id",-1);
                break;
            case 3:
                comment_id = dataBean.getId();
                break;
        }
        if (token == null || token.equals("")){
            OkGo.<String>get(MyConstant.GETCOMMENTS).params("page_index", 0).params("comment_id", comment_id).execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    Gson gson = new Gson();
                    CommentDetailsBean commentDetailsBean = gson.fromJson(s, CommentDetailsBean.class);
                    data = commentDetailsBean.getData();
                    if (data != null) {
                        mDatas.addAll(data);
                    }
                    mRecyclerviewActivityCommentDetails.setLayoutManager(new LinearLayoutManager(CommentDetailsActivity.this));
                    adapter = new CommentDetailsAdapter(R.layout.item_comment_details, mDatas, getSupportFragmentManager());
                    initHead();
                    mRecyclerviewActivityCommentDetails.setAdapter(adapter);
                    deleteComment();

                }
            });
        }else {
            OkGo.<String>get(MyConstant.GETCOMMENTS).params("token", SPUtils.getString(CommentDetailsActivity.this, "token", ""))
                    .params("page_index", 0).params("comment_id", comment_id).execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    Gson gson = new Gson();
                    CommentDetailsBean commentDetailsBean = gson.fromJson(s, CommentDetailsBean.class);
                    data = commentDetailsBean.getData();
                    if (data != null) {
                        mDatas.addAll(data);
                    }
                    mRecyclerviewActivityCommentDetails.setLayoutManager(new LinearLayoutManager(CommentDetailsActivity.this));
                    adapter = new CommentDetailsAdapter(R.layout.item_comment_details, mDatas, getSupportFragmentManager());
                    mRecyclerviewActivityCommentDetails.setAdapter(adapter);
                    initHead();
                    deleteComment();
                }
            });
        }
    }


    /**
     * 获取更多数据
     */
    private void getMoreCommetn() {
        if (token.equals("") || token == null){
            OkGo.<String>get(MyConstant.GETCOMMENTS).params("page_index", pageNum).params("comment_id", comment_id).execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    Gson gson = new Gson();
                    CommentDetailsBean commentDetailsBean = gson.fromJson(s, CommentDetailsBean.class);
                    data = commentDetailsBean.getData();
                    if (data != null) {
                        mDatas.addAll(data);
                    }
                    deleteComment();
                }
            });
        }else {
            OkGo.<String>get(MyConstant.GETCOMMENTS).params("token", SPUtils.getString(CommentDetailsActivity.this, "token", ""))
                    .params("page_index", pageNum).params("comment_id", comment_id).execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    Gson gson = new Gson();
                    CommentDetailsBean commentDetailsBean = gson.fromJson(s, CommentDetailsBean.class);
                    data = commentDetailsBean.getData();
                    if (data != null) {
                        mDatas.addAll(data);
                    }
                    deleteComment();
                }
            });
        }

    }

    /**
     * 初始化头部
     */
    private void initHead() {
        inflater = LayoutInflater.from(this);
        parentView = getWindow().getDecorView().findViewById(android.R.id.content);
        View headView = inflater.inflate(R.layout.item_first_comment, parentView, false);
        CircleImageView ivIcon = headView.findViewById(R.id.iv_activity_comment_details_avatar);
        TextView name = headView.findViewById(R.id.tv_activity_comment_details_name);
        TextView content = headView.findViewById(R.id.tv_activity_comment_text);
        TextView reply = headView.findViewById(R.id.tv_activity_comment_reply);
        praise = headView.findViewById(R.id.tv_activity_comment_praise_num);
        praise.setText(String.valueOf(praiseNum));
        Log.i(TAG, "initHead: "+ praise.getText().toString().trim());
        TextView nextReply = headView.findViewById(R.id.item_head_reply_num);
        TextView mTime = headView.findViewById(R.id.tv_activity_comment_time);
        TextView mDetele = headView.findViewById(R.id.tv_item_first_comment_delete);
        LinearLayout llPraise = headView.findViewById(R.id.ll_item_first_comment);
        imgPraise = headView.findViewById(R.id.iv_item_news_details_praise);
        if (String.valueOf(user_id).equals(SPUtils.getInt(CommentDetailsActivity.this, "id", -1))){
            //本id，显示删除
            llPraise.setVisibility(View.GONE);
            mDetele.setVisibility(View.VISIBLE);
            mDetele.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                        //删除操作
                    new AlertDialog.Builder(CommentDetailsActivity.this).setTitle("删除操作").setMessage("确认删除本条评论吗？").setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            OkGo.<String>delete(MyConstant.DELETE_COMMENT).params("token",token).params("comment_id",comment_id).execute(new StringCallback() {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    Gson gson = new Gson();
                                    PostBean bean = gson.fromJson(s, PostBean.class);
                                    switch (bean.getCode()){
                                        case 1:
                                            finish();
                                            break;
                                    }
                                }
                            });
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    }).show();

                }
            });
        }else {
            mDetele.setVisibility(View.GONE);
            llPraise.setVisibility(View.VISIBLE);
        }
        Log.i(TAG, "initHead: "+time);
        mTime.setText(time);
        name.setText(user_name);
        content.setText(context);
        reply.setText("回复" + "(" +  replyNum+ ")");
        Glide.with(CommentDetailsActivity.this).load(icon_url).into(ivIcon);
        nextReply.setText("全部评论" + "(" + replyNum + ")");
        Log.i(TAG, "initHead: "+isPraise);
        if (isPraise){
            //已经点赞
            imgPraise.setImageResource(R.mipmap.information_praise_after);
            imgPraise.setEnabled(false);
//            praise.setText(String.valueOf(pageNum));
        }else {
            //点赞操作
            imgPraise.setImageResource(R.mipmap.information_praise_before);
            imgPraise.setEnabled(true);
            llPraise.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (SPUtils.getString(CommentDetailsActivity.this, "token", "") == null || SPUtils.getString(CommentDetailsActivity.this, "token", "").equals("")) {
                        startActivity(new Intent(CommentDetailsActivity.this, LoginActivity.class));
                    } else {

                        OkGo.<String>post(MyConstant.MAKE_PRAISE).params("token", SPUtils.getString(CommentDetailsActivity.this, "token", ""))
                                .params("is_praise", true).params("comment_id", comment_id).execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                Gson gosn = new Gson();
                                PostBean bean = gosn.fromJson(s, PostBean.class);
                                if (bean.getCode() == 1) {
                                    final int addPraise = item.getPraise() + 1;
                                    imgPraise.setImageResource(R.mipmap.information_praise_after);
                                    imgPraise.setEnabled(false);
                                    praise.setText(addPraise+"");
                                }


                            }
                        });
                    }
                }
            });

        }

        adapter.addHeaderView(headView);
    }


    @OnClick(R.id.iv_news_details_title_back)
    public void onMIvNewsDetailsTitleBackClicked() {
        finish();
    }


    /**
     * 弹出评论框
     */
    @OnClick(R.id.tv_comment_details)
    public void onViewClicked() {
        if (token==null || token.equals("")){
            startActivity(new Intent(CommentDetailsActivity.this,LoginActivity.class));
            finish();
        }else {
            tipComment();
        }
    }

    /**
     * 弹出评论框
     */
    private void tipComment() {
        EditTextDialog dialog = new EditTextDialog();
        int layoutRes = dialog.getLayoutRes();
        mDialog = BottomDialog.create(getSupportFragmentManager())
                .setViewListener(new BottomDialog.ViewListener() {
                    @Override
                    public void bindView(View v) {
                        initView(v);
                    }
                })
                .setLayoutRes(layoutRes)
                .setDimAmount(0.1f)            // Dialog window dim amount(can change window background color）, range：0 to 1，default is : 0.2f
                .setTag("BottomDialog")     // setting the DialogFragment tag
                .show();
    }
    public void publishComment(int commentId){
        OkGo.<String>post(MyConstant.CREATE_COMMENT).params("comment_id", commentId).params("token", SPUtils.getString(CommentDetailsActivity.this, "token", ""))
                .params("content", commentContext.getText().toString().trim()).execute(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                Gson gson = new Gson();
                PublishCommentBean publishCommentBean = gson.fromJson(s, PublishCommentBean.class);
                switch (publishCommentBean.getCode()) {
                    case 1:
                        showToastLong("发布成功");
                        getServiceComment();
                        adapter.notifyDataSetChanged();
                        mDialog.dismiss();
                        break;
                }
            }
        });
    }
    private void initView(View v) {
        commentContext = v.findViewById(R.id.edt_dialog_comment_context);
        //取消按钮
        v.findViewById(R.id.btn_dialog_comment_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDialog.dismiss();
            }
        });
        /**
         * 确定按钮
         */
        v.findViewById(R.id.btn_dialog_comment_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG, "onClick: " + comment_id);
                if (commentContext.getText().toString().trim().equals("")){
                    showToastLong("请输入内容");
                }else {
                    mDatas.clear();
                    publishComment(comment_id);
                    showToastLong("发布成功");
                }

            }
        });
    }
}
